import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {
  Form,
  Input,
  InputNumber,
  Radio,
  Modal,
  Select,
  Upload,
  message,
  Checkbox,
  DatePicker,
  TreeSelect,
  Button, Space
} from 'antd'
import {t, Trans} from "@lingui/macro"
import ImgCrop from "antd-img-crop";
import {LoadingOutlined, MinusCircleOutlined, PlusOutlined} from "@ant-design/icons";
import moment from 'moment';
import api from '../../../services/api'
import store from "store";
import draftToHtml from "draftjs-to-html";
import draft from "draft-js";import DraftEditor from "../../../components/Editor";import {addRootNode} from "../../../utils/tree";
import TextArea from "antd/es/input/TextArea";
const {createUserAvatar, createAdminContentImage} = api

const {ContentState} = draft
const { Option } = Select;
const FormItem = Form.Item
//时间格式化
const datetimeFormat = "YYYY-MM-DD HH:mm:ss"
const dateFormat = "YYYY-MM-DD"
const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

class CodeTableColumnModal extends PureComponent {
  formRef = React.createRef()

  state = {
    value: [],
    loading: false, //上传 loading
    optionNames:{}, //选项选中值
  };

  constructor(props) {
    super(props);
  }


  handleOk = () => {
    const { item = {}, onOk } = this.props
    this.formRef.current.validateFields()
      .then(values => {
        const data = {
          ...values,
          id: item.id,
          //时间值处理
        }

        let comment = "";
        let optionStr = ""
        values.optionItems && values.optionItems.map((v,k)=>{
          if(v.name == "option") {
            optionStr = v.value
          } else {
            comment += v.name + ":" + v.value
            if(k != (values.optionItems.length - 1)) {
              comment += ","
            }
          }
        })
        comment = (values.title ? values.title : "") +";"+optionStr+";" + comment
        data.comment = comment
        delete data.optionItems
        onOk(data)
      })
      .catch(errorInfo => {
        console.log(errorInfo)
      })
  }

  /**
   * 解析扩展数据
   *
   * @param item
   * @returns {[]}
   */
  parseExtendItems = (item) => {
    let comment = item.comment
    let title = item.title;
    let extendOptions = ""
    let extendItems = []
    if(comment) {
      let parts = comment.split(";")
      if(parts.length>0) {
        //   //title
        title = parts[0]
        if(parts.length>=2) {
          extendOptions = parts[1]
        }
        if(parts.length>=3) {
          let extendParts = parts[2].split(",")
          for(let i=0; i<extendParts.length; i++) {
            let tmpParts = extendParts[i].split(":")
            console.log(extendParts[i])
            if(tmpParts.length==2) {
              extendItems.push({name: tmpParts[0], value: tmpParts[1]})
            }
          }
        }
      }
    }
    //检查填充option
    if(extendOptions && extendOptions != "") {
      extendItems.push({name:'option', value: extendOptions})
    }
    return extendItems;
  }

  render() {
    const { item = {}, onOk, form,options,trees, ...modalProps } = this.props

    const tableIdOptionData = Object.keys(options.tableId).map((k,index)=>{
      return {value: parseInt(k), label: options.tableId[k]}
    })
    const dataTypeOptionData = Object.keys(options.dataType).map((k,index)=>{
      return {value: k, label: options.dataType[k]}
    })
    const isPkOptionData = Object.keys(options.isPk).map((k,index)=>{
      return {value: parseInt(k), label: options.isPk[k]}
    })
    const isNotNullOptionData = Object.keys(options.isNotNull).map((k,index)=>{
      return {value: parseInt(k), label: options.isNotNull[k]}
    })
    const isUniqueOptionData = Object.keys(options.isUnique).map((k,index)=>{
      return {value: parseInt(k), label: options.isUnique[k]}
    })
    const isAutoIncrementOptionData = Object.keys(options.isAutoIncrement).map((k,index)=>{
      return {value: parseInt(k), label: options.isAutoIncrement[k]}
    })
    const isZeroFillOptionData = Object.keys(options.isZeroFill).map((k,index)=>{
      return {value: parseInt(k), label: options.isZeroFill[k]}
    })

    //处理解析扩展项数据
    let extendItems = this.parseExtendItems(item)

    let initData = {...item};
    initData['optionItems'] = extendItems
    let optionNames = {}
    for(let i=0; i< extendItems.length; i++) {
      optionNames[i] = extendItems[i].name;
    }
    this.state['optionNames'] = {...optionNames,...this.state.optionNames}

    //初始化title
    if(!item.title) {
      let comment = item.comment;
      if(comment) {
        let parts = comment.split(";")
        if(parts.length>0) {
          initData.title = parts[0]
        }
      }
    }

    //初始化时间处理
    return (

      <Modal {...modalProps} onOk={this.handleOk} width={1300}>
        <Form ref={this.formRef} name="control-ref" initialValues={{ ...initData }} layout="horizontal">

         <FormItem  name='tableId' rules={[{ required: false }]}
            label={t`Table Name`} hasFeedback {...formItemLayout}>
           <Select
             showSearch
             placeholder={t`Table Id`}
             optionFilterProp="children"
             options={tableIdOptionData}
             />
          </FormItem>
         <FormItem  name='name' rules={[{ required: false }]}
            label={t`Name`} hasFeedback {...formItemLayout}>
            <Input maxLength={45} />
          </FormItem>
         <FormItem  name='title' rules={[{ required: false }]}
            label={t`Title`} hasFeedback {...formItemLayout}>
            <Input maxLength={45} />
          </FormItem>
         <FormItem  name='dataType' rules={[{ required: false }]}
            label={t`Data Type`} hasFeedback {...formItemLayout}>
           <Select
             showSearch
             placeholder={t`Data Type`}
             optionFilterProp="children"
             options={dataTypeOptionData}
             />
          </FormItem>
         <FormItem  name='isPk' rules={[{ required: false }]}
            label={t`Is Pk`} hasFeedback {...formItemLayout}>
           <Select
             showSearch
             placeholder={t`Is Pk`}
             optionFilterProp="children"
             options={isPkOptionData}
             />
          </FormItem>
         <FormItem  name='isNotNull' rules={[{ required: false }]}
            label={t`Is Not Null`} hasFeedback {...formItemLayout}>
           <Select
             showSearch
             placeholder={t`Is Not Null`}
             optionFilterProp="children"
             options={isNotNullOptionData}
             />
          </FormItem>
         <FormItem  name='isUnique' rules={[{ required: false }]}
            label={t`Is Unique`} hasFeedback {...formItemLayout}>
           <Select
             showSearch
             placeholder={t`Is Unique`}
             optionFilterProp="children"
             options={isUniqueOptionData}
             />
          </FormItem>
         <FormItem  name='isAutoIncrement' rules={[{ required: false }]}
            label={t`Is Auto Increment`} hasFeedback {...formItemLayout}>
           <Select
             showSearch
             placeholder={t`Is Auto Increment`}
             optionFilterProp="children"
             options={isAutoIncrementOptionData}
             />
          </FormItem>
         <FormItem  name='isZeroFill' rules={[{ required: false }]}
            label={t`Is Zero Fill`} hasFeedback {...formItemLayout}>
           <Select
             showSearch
             placeholder={t`Is Zero Fill`}
             optionFilterProp="children"
             options={isZeroFillOptionData}
             />
          </FormItem>
         <FormItem  name='defaultValue' rules={[{ required: false }]}
            label={t`Default Value`} hasFeedback {...formItemLayout}>
            <Input maxLength={1000} />
          </FormItem>
         <FormItem  name='length' rules={[{ required: false }]}
            label={t`Length`} hasFeedback {...formItemLayout}>
            <InputNumber max={99999999999}  style={{width:200}} />
          </FormItem>
         <FormItem  name='scale' rules={[{ required: false }]}
            label={t`Scale`} hasFeedback {...formItemLayout}>
            <InputNumber max={99999999999}  style={{width:200}} />
          </FormItem>
         <FormItem  name='comment' rules={[{ required: false }]}
            label={t`Comment`} hasFeedback {...formItemLayout}>
            <Input maxLength={3000} />
          </FormItem>

          <FormItem  name='extend' rules={[{ required: false }]}
                     label={t`Extend Data`} hasFeedback {...formItemLayout}>
            <Form.List name="optionItems" style={{margin: "350px"}} rules={[{required: false}]} hasFeedback >
              {(fields, { add, remove }) => (

                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} size={"middle"} align="baseline">
                      <Form.Item
                        {...restField}
                        name={[name, 'name']}
                        rules={[{required: false}]} >
                        <Select
                                placeholder={"请选择扩展项名称"}
                                onChange={(e)=>{
                                  let optionNames = this.state.optionNames
                                  optionNames[key] = e
                                  this.setState({optionNames: optionNames})
                                }}>
                          <Select.Option value="frontType">frontType</Select.Option>
                          <Select.Option value="frontName">frontName</Select.Option>
                          <Select.Option value="javaType">javaType</Select.Option>
                          {/*<Select.Option value="frontHome">frontHome</Select.Option>*/}
                          <Select.Option value="uploadCount">uploadCount</Select.Option>
                          <Select.Option value="ignoreInList">ignoreInList</Select.Option>
                          <Select.Option value="foreign">foreign</Select.Option>
                          {/*<Select.Option value="tree">tree</Select.Option>*/}
                          {/*<Select.Option value="parent">parent</Select.Option>*/}
                          <Select.Option value="option">option</Select.Option>
                          <Select.Option value="isFilter">isFilter</Select.Option>
                          <Select.Option value="isApproval">isApproval</Select.Option>
                          <Select.Option value="editReadOnly">editReadOnly</Select.Option>
                          <Select.Option value="isEnum">isEnum</Select.Option>
                        </Select>
                      </Form.Item>
                      {/*java类型选择*/}
                      {this.state.optionNames[key] && this.state.optionNames[key]=="javaType" && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <Select placeholder={"请选择Java类型"}>
                          <Select.Option value={"Integer"}>Integer</Select.Option>
                          <Select.Option value={"String"}>String</Select.Option>
                          <Select.Option value={"Date"}>Date</Select.Option>
                        </Select>
                      </Form.Item>}
                      {/*frontType选择*/}
                      {this.state.optionNames[key] && this.state.optionNames[key]=="frontType" && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <Select placeholder={"请选择前端类型"} >
                          <Select.Option value="text">Text</Select.Option>
                          <Select.Option value="select">Select</Select.Option>
                          <Select.Option value="treeSelect">TreeSelect</Select.Option>
                          <Select.Option value="checkbox">Checkbox</Select.Option>
                          <Select.Option value="textarea">Textarea</Select.Option>
                          <Select.Option value="editor">editor</Select.Option>
                          <Select.Option value="datetime">datetime</Select.Option>
                          <Select.Option value="date">date</Select.Option>
                          <Select.Option value="upload">upload</Select.Option>
                          <Select.Option value="number">number</Select.Option>
                          <Select.Option value="password">password</Select.Option>
                        </Select>
                      </Form.Item>}
                      {/*uploadSize  Number*/}
                      {this.state.optionNames[key] && this.state.optionNames[key]=="uploadCount" && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <InputNumber defaultValue={1} value={1} />
                      </Form.Item>}
                      {/*Input*/}
                      {this.state.optionNames[key] && (this.state.optionNames[key]=="frontName"
                        // || this.state.optionNames[key]=="foreign"
                        || this.state.optionNames[key]=="tree"
                        || this.state.optionNames[key]=="option"

                      ) && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <Input />
                      </Form.Item>}
                      {/*Input*/}
                      {this.state.optionNames[key] && (
                         this.state.optionNames[key]=="foreign"
                         || this.state.optionNames[key]=="parent"

                      ) && <Form.Item tooltip={{trigger: "hover",placement: 'rightTop',color:"red", title:"样例：pay_info.id~name; [表名字].[Key字段]~[显示名字段]"}}
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <Input />
                      </Form.Item>}
                      {/*Bool Select*/}
                      {this.state.optionNames[key] && (
                        this.state.optionNames[key]=="isFilter"
                        || this.state.optionNames[key]=="ignoreInList"
                        || this.state.optionNames[key]=="isApproval"
                        || this.state.optionNames[key]=="editReadOnly"
                        || this.state.optionNames[key]=="isEnum"
                      ) && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <Select defaultValue={true} placeholder={"请选择"}>
                          <Select.Option value={false}>否</Select.Option>
                          <Select.Option value={true}>是</Select.Option>
                        </Select>
                      </Form.Item>}
                      {/*Front Home Select*/}
                      {this.state.optionNames[key] && this.state.optionNames[key]=="frontHome" && <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        style={{width: 100}}
                        rules={[{required: false}]} >
                        <Select defaultValue={"list"}>
                          <Select.Option value={"list"}>List</Select.Option>
                          <Select.Option value={"tree"}>Tree</Select.Option>
                        </Select>
                      </Form.Item>}


                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}

                  <Form.Item>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                      {/*Add Extend Data Item*/}
                      添加扩展项
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </FormItem>

        </Form>
      </Modal>
    )
  }
}

CodeTableColumnModal.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}

export default CodeTableColumnModal

